/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
package SteamEngineFX.data;

import SteamEngineDB.*;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import org.joda.time.LocalDate;


/**
 *
 * @author jbendixsen
 */
public class ScheduleController extends BaseController{
    
    public ScheduleController(SteamEngineConnection sec) {
        super(sec);
        
    }
    
    public Schedule loadSchedule(LocalDate date){
        
        // get or create schedule for selected date
        Schedule s = getSchedule(date);
        if (s == null){
            return newSchedule(date);
        }
        return s;
    }
    
    public Schedule getSchedule(LocalDate date){
        
        long mark = System.currentTimeMillis();
        
        List<Schedule> schedules = getEM().createNamedQuery("Schedule.findByScheduleDate")
                .setParameter("scheduleDate", date.toDate())
                .getResultList();
        
        if (schedules.size() > 0){
            System.out.printf("Loaded schdule for %s in %dms \n", date.toString(), System.currentTimeMillis() - mark);
            return schedules.get(0);
        }
        return null;
    }
    
    public Schedule newSchedule(){
        LocalDate today = new LocalDate(); 
        return newSchedule(today);
    }
    public Schedule newSchedule(LocalDate date){
        
        //get default template
        List<Template> templates = getEM().createNamedQuery("Template.findByDefaultSchedule")
                                                   .setParameter("defaultSchedule", "True")
                                                   .getResultList();
        if (templates.size() > 0)
        {
            int id = templates.get(0).getId();
            return insertSchedule(date, id);
        }
        return null;
    }
    
    public Schedule newSchedule(LocalDate date, Template template){
    
        if (template != null){
            return insertSchedule(date, template.getId());    
        }
        return null;
    }
    
    private Schedule insertSchedule(LocalDate date, int templateId){
        
        long mark = System.currentTimeMillis();
        
        //Excpect a default template
        List<Template> templates = getEM().createNamedQuery("Template.findById")
                                           .setParameter("id", templateId)
                                           .getResultList();
        //TODO: hadle this nicer
        // for instance create a template
        if (templates.size() == 0) return null;
        
        Template template = templates.get(0);
        Schedule schedule = null;
        
        EntityManager conn = getEM();
        EntityTransaction trans = null;
        try{
            trans = conn.getTransaction();
            trans.begin();
        
            //define the new schedule object and set the date
            schedule = new Schedule();
            schedule.setScheduleDate(date.toDate());

            //save and flush to get an ID
            conn.persist(schedule);
            conn.flush();
    
            for(Iterator<TemplateRun> i = template.getTemplateRunCollection().iterator(); i.hasNext();){
                    
                TemplateRun templateRun = i.next();
            
                ScheduleRun run = new ScheduleRun();
                run.setRunTime(templateRun.getRunTime());
                run.setScheduleId(schedule);

                conn.persist(run);
                conn.flush();

                for(Iterator<TemplateCar> j = templateRun.getTemplateCarCollection().iterator(); j.hasNext();){

                    TemplateCar templateCar = j.next();

                    ScheduleCar Car = new ScheduleCar();
                    Car.setRunId(run);
                    Car.setCarId(templateCar.getCar());
                    Car.setPosition(templateCar.getPosition());

                    conn.persist(Car);
                    //conn.flush();
                }
            }
            trans.commit();
            conn.refresh(schedule);
             
            System.out.printf("Created schdule for %s in %dms \n", date.toString(), System.currentTimeMillis() - mark);
             
        }catch(RuntimeException ex){
            if ((trans != null) && (trans.isActive())) trans.rollback();
            schedule = null;
            System.out.println("Error creating schedule: " + ex.getMessage());
        }
        finally{
            conn.close();
        }
        return schedule;
    }
    
}
